// new-components/getPhone/get-phone.js
Component({
  options:{
    addGlobalClass: true,
    state:false
  },
  lifetimes:{
    attached(){
      var t=this;
      wx.login({
        success(e){
          console.log(e)
          t.setData({code:e.code})
        }
      })
      this.setData({
        customerId:wx.getStorageSync('customerId'),
        token:wx.getStorageSync('ACCESS_TOKEN')
      })

    }
  },
  methods: {
    getPhoneNumber: function(o) {
      var that=this;
      "getPhoneNumber:fail user deny" == o.detail.errMsg ?
        getApp().bus.showToast('未授权') :that.decodePhone(o,that.data.code)
    },
    decodePhone(o,code){
      var that=this;
      getApp().request({
        url: getApp().api.user.user_binding,
        data: {
          iv: o.detail.iv,
          encryptedData: o.detail.encryptedData,
          code: code
        },
        success(e) {
          console.log(e)
          0 == e.code ?
            that.getAppUserInfo(e.data.phone) :
            getApp().bus.showToast(e.msg)
        }
      });
    },
    getAppUserInfo(p){
      var that = this;
      getApp().request({
        url:getApp().api.user.customer_wx_info,
        data:{
          mobile:p,
          storeId:getApp().api.siteinfo.acid
        },
        success(e){
          if(e.result==0){
            that.setData({customerId:e.data.customerId})
            getApp().bus.showToast('授权成功')
            getApp().customerId = e.data.customerId
            wx.setStorageSync('appUserInfo',e.data)
            wx.setStorageSync('customerId',true)
            that.onLoad()
          }else {
            getApp().bus.showToast('授权失败,请重试')
          }
        }
      })
    },
    onLoad(){
      var pages = getCurrentPages();
      var n = pages[pages.length - 1];
      wx.redirectTo({
        url: "/" + n.route + "?" + getApp().helper.objectToUrlParams(n.options)
      })
    }
  }
})
